package com.example.demo.controller;/**
 * ClassName: UserController
 * Package: com.example.demo.controller
 * Description:
 *
 * @Author 理理
 * @Create 2024/11/16 16:03
 * @Version 1.0
 */

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;

import java.util.List;

/**
 *
 *@title: UserController
 *@Author: Tangerine
 *@Date: 2024/11/16 16:03
 *@version 1.0
 */

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @GetMapping("/")
    public List<User> index() { return userMapper.findAll(); }
    //注册用户
    @PostMapping("/register")
    public ResponseEntity<User> registerUser(@RequestParam String studentNumber,@RequestParam String password){

            User registeredUser = userService.register(studentNumber,password);
            return new ResponseEntity<>(registeredUser, HttpStatus.CREATED);
    }

    @PostMapping("/login")
    public ResponseEntity<User> loginUser(@RequestParam String studentNumber,@RequestParam String password){
        User loginUser = userService.login(studentNumber,password);
            if(loginUser!=null){
                return new ResponseEntity<>(loginUser, HttpStatus.CREATED);
            }
            else {
                throw new IllegalArgumentException("StudentNumber or Password was wrong.");
            }
    }

    @PostMapping("/update")
    public ResponseEntity<User> updateUser(@RequestParam String studentNumber,@RequestParam String password){
        User loginUser = userService.update(studentNumber,password);
        if(loginUser!=null){
            return new ResponseEntity<>(loginUser, HttpStatus.CREATED);
        }
        else {
            throw new IllegalArgumentException("StudentNumber already exists.");
        }
    }

}
